<template>
	<view class="lb-countdown">
		<text class="time-seg">{{hours}}</text>
		<text class="sep">:</text>
		<text class="time-seg">{{minutes}}</text>
		<text class="sep">:</text>
		<text class="time-seg">{{seconds}}</text>
	</view>
</template>

<script>
	export const ONE_HOUR = 60 * 60 * 1000;
	export const ONE_MINUTE = 60 * 1000;
	export default {
		data() {
			return {
				hours: '00',
				minutes: '00',
				seconds: '00',
				remainMills: 0,
				time: -1
			};
		},
		props: {
			mills: {
				type: Number,
				default: 60 * 60 * 1000
			}
		},
		watch: {
			mills(val) {
				this.remainMills = val;
				this.startTime();
			}
		},
		beforeDestroy() {
			this.stopTime();
		},
		mounted() {
			this.remainMills = this.mills;
			this.startTime();
		},
		methods: {
			startTime() {
				if (this.time > 0 ||this.remainMills <= 0) {
					return;
				}
				this.updateTime();
				this.time = setInterval(()=>{
					if (this.remainMills <= 0) {
						this.$emit("timeup");
						this.stopTime();
						return;
					}
					this.remainMills -= 1000;
					this.updateTime();
				}, 1000);
			},
			stopTime() {
				if (this.time > 0) {
					clearInterval(this.time);
					this.time = -1;
				}
			},
			updateTime() {
				let h = Math.floor(this.remainMills / ONE_HOUR);
				if (h < 10) {
					this.hours = `0${h}`;
				} else {
					this.hours = `${h}`;
				}
				let m = Math.floor((this.remainMills % ONE_HOUR) / ONE_MINUTE);
				if (m < 10) {
					this.minutes = `0${m}`;
				} else {
					this.minutes = `${m}`;
				}
				let s = Math.floor(((this.remainMills % ONE_HOUR) % ONE_MINUTE) / 1000);
				if (s < 10) {
					this.seconds = `0${s}`;
				} else {
					this.seconds = `${s}`;
				}
			}
		}
	}
</script>

<style lang="scss">
	.lb-countdown {
		color: #D61719;
		.time-seg {
			// background-color: rgba(255,129,108,0.5);
			// padding: 0 4rpx;
		}
		.sep {
			margin: 0 4rpx;
		}
	}
</style>
